package com.itdaan.portal.business.controller;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.itdaan.portal.business.domain.Permission;
import com.itdaan.portal.business.domain.Role;
import com.itdaan.portal.business.domain.RolePermission;
import com.itdaan.portal.business.service.PermissionService;
import com.itdaan.portal.business.service.RolePermissionService;
import com.itdaan.portal.business.service.RoleService;
import com.itdaan.portal.common.exception.ServiceException;

/**
 * 角色业务管理类
 * @author www.itdaan.com
 */
@Controller
@RequestMapping("/user/role")
public class RoleController {
	
	private Logger logger = LoggerFactory.getLogger(RoleController.class);
	
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RolePermissionService rolePermissionService;


	@RequestMapping(value = "edit")
	public String edit(@ModelAttribute("preloadRole") Role role, Model model) {
		List<Permission> permissions = new ArrayList<Permission>();
		try {
			permissions = permissionService.getAll();
		} catch (ServiceException e) {
			logger.error("查询权限信息失败：{}",e.toString());
		}
		// 用于给之前选中的权限设置选中状态
		List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
		try {
			rolePermissions = rolePermissionService.getByRoleId(role.getId());
		} catch (ServiceException e) {
			logger.error("查询权限信息失败：{}",e.toString());
		}
		int[] permissionIds = new int[rolePermissions.size()];
		for (int i = 0; i < rolePermissions.size(); i++) {
			permissionIds[i] = rolePermissions.get(i).getPermissionId();
		}
		
		model.addAttribute("role", role);
		model.addAttribute("permissions", permissions);
		model.addAttribute("permissionIds", permissionIds);
		return "user/role_edit";
	}

	@RequiresPermissions("role:save")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(
			@ModelAttribute("preloadRole") Role role,
			@RequestParam(value = "permissionIds", required = false) int[] permissionIds) {
		if (role.getId() == 0) {// 新增
			try {
				roleService.insert(role);
			} catch (ServiceException e) {
				logger.error("保存角色失败：{}",e.toString());
			}
		} else {// 修改
			try {
				roleService.update(role);
			} catch (ServiceException e) {
				logger.error("修改角色失败：{}",e.toString());
			}
		}
		
		// 处理角色拥有的权限（映射表），先删后加
		int id = role.getId();
		try {
			rolePermissionService.deleteByRoleId(id);
		} catch (ServiceException e) {
			logger.error("删除角色权限失败：{}",e.toString());
		}
		if (ArrayUtils.isNotEmpty(permissionIds)) {
			for (int permissionId : permissionIds) {
				RolePermission rolePermission = new RolePermission();
				rolePermission.setRoleId(id);
				rolePermission.setPermissionId(permissionId);
				try {
					rolePermissionService.insert(rolePermission);
				} catch (ServiceException e) {
					logger.error("角色权限插入失败：{}",e.toString());
				}
			}
		}
		return "redirect:/user/role";
	}
	
	@RequiresPermissions("role:delete")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam("ids") String ids) {
		// 由于设置了外键级联删除，会同步删除映射表中的数据
		try {
			roleService.deleteByIds(ids);
		} catch (ServiceException e) {
			logger.error("角色删除失败：{}",e.toString());
		}
		return "redirect:/user/role";
	}
	
	@RequestMapping(value = StringUtils.EMPTY)
	public String list(Model model) {
		List<Role> roles = new ArrayList<Role>();
		try {
			roles = roleService.getAll();
		} catch (ServiceException e) {
			logger.error("查询角色信息失败：{}",e.toString());
		}
		model.addAttribute("roles", roles);
		return "user/role_list";
	}
	
	@ModelAttribute("preloadRole")
	public Role getRole(
			@RequestParam(value = "id", required = false) Integer id) {
		if (id != null && id != 0) {
			try {
				return roleService.getById(id);
			} catch (ServiceException e) {
				logger.error("查询角色信息失败：{}",e.toString());
			}
		}
		return new Role();
	}
	
}
